package com.ptp.backendcertms.login.controller;

import com.ptp.backendcertms.api.external.dto.req.LoginReqDto;
import com.ptp.backendcertms.api.external.dto.res.LoginResDto;
import com.ptp.backendcertms.api.external.dto.res.ResponseDto;
import com.ptp.backendcertms.api.internal.exception.SystemException;
import com.ptp.backendcertms.api.internal.constant.SystemResponseEnum;
import com.ptp.backendcertms.basiccompnents.data.dao.entity.SettingLoginUserPo;
import com.ptp.backendcertms.basiccompnents.data.dao.service.ISettingLoginUserService;
import com.ptp.backendcertms.basiccompnents.http.ResponseWrapper;
import com.ptp.backendcertms.token.service.ITokenService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.Objects;

/**
 * 登录接口
 */
@Slf4j
@RestController
public class LoginController {

    @Resource
    private ISettingLoginUserService settingLoginUserService;
    @Resource
    private ITokenService tokenService;


    @PostMapping("/login")
    public ResponseDto<LoginResDto> login(@RequestBody @Valid LoginReqDto loginBody, BindingResult bindingResult) {
        return ResponseWrapper.responseReturnWithValid(bindingResult, "登录接口", () -> {
            SettingLoginUserPo po = settingLoginUserService.selectLogin(loginBody.getUserName(), loginBody.getPassword());
            if (Objects.isNull(po)) {
                throw new SystemException(SystemResponseEnum.USER_NOT_EXISTS_FAIL.name(), "用户名或密码不存在");
            }
            String token = tokenService.createToken(po.getUserName(), 7 * 24 * 3600 * 1000L);
            LoginResDto resDto = new LoginResDto();
            resDto.setToken(token);
            resDto.setUserName(po.getUserName());
            return resDto;
        });
    }


}
